<template>
  <a-form
    :model="CiBao ? CibaoFormFields : BwFormFields"
    :rules="formRules"
    hideRequiredMark
    class="flex flex-nowrap query-fields"
    label-align="left"
    layout="inline"
    ref="FormRef"
  >
    <a-form-item label="产品" name="type">
      <a-radio-group button-style="solid" v-model:value="type">
        <a-radio-button :value="ProductEnum.BW">标王</a-radio-button>
        <a-radio-button :value="ProductEnum.CiBao">词包</a-radio-button>
      </a-radio-group>
    </a-form-item>
    <a-row class="flex-1" v-if="CiBao || CBYXB">
      <a-col :span="8">
        <a-form-item name="packageId" label="套餐" class="package-control">
          <a-select
            v-model:value="CibaoFormFields.packageId"
            placeholder="请选择套餐"
            :options="packageList"
            @change="emit('cibao-package-change', $event)"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="CiBao" :span="8">
        <a-form-item label="推广时长" name="comboPriceId">
          <a-select
            allow-clear
            placeholder="请选择推广时长"
            v-model:value="CibaoFormFields.comboPriceId"
            :options="comboPriceList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="CiBao" :span="8">
        <a-form-item name="searchText" label="关键词">
          <a-input
            allow-clear
            placeholder="请输入关键词"
            :disabled="submitting"
            v-model:value.trim="CibaoFormFields.keyword"
          />
        </a-form-item>

        <!-- -->
      </a-col>
    </a-row>
    <div v-if="CiBao || CBYXB" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="emit('cibao-submit')">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <a-form-item
      v-if="BW || BWYXB"
      label="推广区域"
      @click="handleServiceAreaClick"
      class="area-disable"
      name="serviceAreas"
    >
      <a-select
        placeholder="请选择推广区域"
        :max-tag-count="2"
        mode="multiple"
        :value="BwFormFields.serviceAreas"
        :options="serviceAreasOptions"
        disabled
      />
    </a-form-item>
    <a-form-item v-if="BW || BWYXB" label="用户所在地" name="userAreas" class="user-areas">
      <a-select show-search placeholder="请选择用户所在地" v-model:value="userAreas" :options="serviceAreasOptions" />
    </a-form-item>
  </a-form>
  <div class="mt-4 mb-1" v-if="BW || BWYXB">
    <bw-textarea
      v-model:text="text"
      :submitting="bwSubmitting"
      :type="type"
      @submit="beforeSubmit"
      @reset="handleReset"
    />
  </div>
  <BwArea v-model:show="visible" @change="handleAreaChange" ref="BwAreaRef" />
</template>

<script lang="ts" setup>
import { useVModel } from '@vueuse/core'
import type { PackageData } from '@/services/price-sheet/getPackageList'
import { computed, ref, watch } from 'vue'
import BwArea from '@/views/price-sheet/components/BwArea.vue'
import type { BwPriceAskParams } from '@/services/price-sheet/getBwPriceAskWords'
import type { CiBaoPriceAskParams } from '@/services/price-sheet/getKeywordList'
import { type FormInstance, message } from 'ant-design-vue'
import type { ComboPrice } from '@/services/price-sheet/getComboPriceList'
import { isEqual, uniq } from 'lodash-es'
import { useCategory } from '@/hooks/useCategotry'
import { emojiMatcher } from '@/utils'
import { ProductEnum } from '@/core/enums/platform'
import BwTextarea from '@/views/price-sheet/components/BwTextarea.vue'
import { useRoute } from 'vue-router'
const route = useRoute()
interface Props {
  packageList: PackageData[]
  comboPriceList: ComboPrice[]
  comboPriceLoading: boolean
  submitting: boolean
  bwSubmitting: boolean
  getResult: boolean
  type: ProductEnum
  bw: BwPriceAskParams
  cibao: CiBaoPriceAskParams
}

interface Emits {
  (e: 'cibao-submit'): void
  (e: 'cibao-reset'): void
  (e: 'cibao-package-change', v: number): void
  (e: 'bw-submit'): void
  (e: 'bw-reset'): void
  (e: 'bw-reset-with-area'): void
}

const FormRef = ref<FormInstance>()
const BwAreaRef = ref<any>()
const emit = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {
  type: ProductEnum.BW,
  getResult: false
})
const type = useVModel(props, 'type')
const showNextStep = useVModel(props, 'getResult')
const visible = ref(false)
const BwFormFields = useVModel(props, 'bw')
const serviceAreas = ref<BwPriceAskParams['serviceAreas']>([])
const CibaoFormFields = useVModel(props, 'cibao')
const { CiBao, BW, BWYXB, CBYXB } = useCategory(type)

const formRules = computed(() => {
  if (BW.value || BWYXB.value) {
    return {
      serviceAreas: [{ required: true, message: '请选择推广区域', trigger: 'change' }],
      userAreas: [{ required: true, message: '请选择用户所在地', trigger: 'change' }]
    }
  } else {
    return {}
  }
})

const text = ref('')

const userAreas = computed({
  set(val?: string) {
    BwFormFields.value.userAreas = val ? [val] : []
  },
  get() {
    return BwFormFields.value.userAreas[0]
  }
})

const serviceAreasOptions = computed(() => {
  return serviceAreas.value.reduce<{ label: string; value: string }[]>((prev, next) => {
    prev.push({
      label: next,
      value: next
    })
    return prev
  }, [])
})

function handleServiceAreaClick() {
  visible.value = true
}

function handleAreaChange(cityMap: Record<string, string[]>) {
  console.log('cityMap', cityMap)
  serviceAreas.value = Object.keys(cityMap).reduce<string[]>((data, key) => {
    return data.concat(cityMap[key])
  }, [])

  console.log('serviceAreas', serviceAreas.value)

  if (!isEqual(BwFormFields.value.serviceAreas, serviceAreas.value)) {
    showNextStep.value = false

    if (BwAreaRef.value.countryWide) {
      BwFormFields.value.serviceAreas = ['全国']
    } else {
      BwFormFields.value.serviceAreas = serviceAreas.value
    }
  }
}

function beforeSubmit() {
  if (BW.value || BWYXB.value) {
    FormRef.value?.validate().then(() => {
      if (emojiMatcher(text.value)) {
        return message.error('推广关键词中存在如：表情等非法字符')
      }

      const participle = text.value
        .toLowerCase()
        .split(/[\n\r\s,，;；]+/g)
        .filter((t) => t !== '')

      if (participle.length === 0) {
        message.error('请输入推广关键词')
      } else {
        BwFormFields.value.priceAskWords = uniq(participle)
        emit('bw-submit')
      }
    })
  }
}

function handleReset() {
  emit('bw-reset')
}

function handleBwReset() {
  text.value = ''
  BwAreaRef.value.handleReset()
}

defineExpose({
  handleBwReset
})

watch(
  () => serviceAreasOptions.value,
  (options) => {
    if (!options.some((d) => d.value === userAreas.value)) {
      userAreas.value = ''
    }
  }
)
</script>

<style lang="scss" scoped>
.query-fields {
  height: 32px;
}

.area-disable {
  width: 280px;
  height: 32px;

  ::v-deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
    background: transparent;
    color: inherit;
    cursor: pointer;
  }

  ::v-deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
    color: inherit;
    cursor: pointer;
  }
}

.user-areas {
  width: 273px;
  height: 32px;
}

.cibao-submit {
  min-width: 138px;
}

.package-control {
  ::v-deep(.ant-form-item-control) {
    overflow: hidden;
  }
}
</style>
